/**
 * Created by DevilsEyes on 2016/1/11.
 */
var loading = {
    $window: null,
    $bar: null,
    $title: null,
    ready: false,
    show: function (title) {
        if (!this.ready)return;
        var x = this;
        x.$window.show();
        x.$bar.width(0);
        x.$title.text(title || '正在加载中');
        return x;
    },
    hide: function () {
        if (!this.ready)return;
        var x = this;
        x.$window.hide();
        x.$bar.width(0);
        return x;
    },
    set: function (rate, title) {
        if (!this.ready)return;
        rate = +rate || 0;
        var x = this;
        var percent = rate * 100 + '%';
        x.$title.text(title || '正在加载中');
        x.$bar.width(percent);
        return x;
    },
    done: function (title) {
        if (!this.ready)return;
        var x = this;
        x.set(1, title || '正在加载中');
        setTimeout(function () {
            x.hide();
        }, 200);
    },
    init: function () {
        var x = this;
        $(document).ready(function () {
            x.$window = $('#loading');
            x.$bar = $('.bar-light', x.$window);
            x.$title = $('span', x.$window);
            x.ready = true;
        });
        return x;
    }
}.init();

var app = (function () {
    var _ = {
        appId: 'wxf72ed77c92113ec4',
        path: {
            wxAuth: 'https://open.weixin.qq.com/connect/oauth2/authorize',
            wsApi: 'http://api.dev.wenshendaka.com/',
            self: location.origin + location.pathname
        },
        getWxAuth: function () {
            var state = params.hash ? params.hash : 'question';
            location.href = _.path.wxAuth + '?appid=' + _.appId + '&redirect_uri=' + encodeURI(_.path.self) + '&response_type=code&scope=snsapi_userinfo&state=' + state + '#wechat_redirect';
            //location.href = _.path.self + '?state=' + state;
        }
    };

    var ready = {
        list: {
            wxAuth: false,
            wxSDK: false,
            dom: false
        },
        count: 0,
        end: 0,
        done: function (str, callback) {
            this.list[str] = true;
            loading.set(this.count / (this.end + 1));

            for (var i in this.list) {
                if (!this.list[i])return false;
            }
            return callback();
        },
        init: function () {
            for (var i in this.list) {
                this.end++;
            }
            return this;
        }
    }.init();

    var params = {
        data: {},
        hash: '',
        get: function () {

            var x = this;
            x.data = {};
            x.hash = location.hash.replace('#', '');
            location.search.replace(/([^?&=]+)(?:={0,1})([^?&]*)/g, function (str, key, value) {
                x.data[key] = value;
                return str;
            });

            return this;
        }
    }.get();

    var app = {
        debug: false,
        tmp: {},
        jsonp: function (map) {
            map.data = map.data || {};
            map.data._method = map.method || 'GET';

            $.jsonp({
                url: map.url,
                data: map.data,
                callbackParameter: map.callbackParameter || 'callback',
                success: function (obj) {
                    if (typeof obj == 'string')obj = JSON.parse(obj);

                    if (app.debug) {
                        alert(map.url + '\n=================\n' + ex.p(map.data, 'log') + '\n=================\n' + ex.p(obj, 'log'));
                    }

                    if (map.success) {
                        map.success(obj)
                    }
                },
                fail: function () {
                    if (app.debug) {
                        alert(map.url + '\n=================\n' + ex.p(map.data, 'log') + '\n=================\nFailed');
                    }
                },
                error: function () {
                    if (app.debug) {
                        alert(map.url + '\n=================\n' + ex.p(map.data, 'log') + '\n=================\nError');
                    }
                }
            })

        },
        init: function (callback) {
            var x = this;
            if (params.data.state) {

                location.hash = '#' + decodeURI(params.data.state);

                //获取微信验证
                app.jsonp({
                    url: _.path.wsApi + 'new/h5/unionId',
                    data: {
                        code: params.data.code
                    },
                    method: 'GET',
                    success: function (obj) {
                        if (obj.code == 0) {
                            x.info.unionId = obj.data;
                            ready.done('wxAuth', callback)
                        } else {
                            _.getWxAuth();
                        }
                    }
                });
                //ready.done('wxAuth', callback);

                //初始化微信SDK
                app.jsonp({
                    url: _.path.wsApi + "new/h5/jsSdkConfig",
                    data: {
                        url: location.href.split('#')[0]
                    },
                    method: 'GET',
                    success: function (obj) {
                        if (obj.code == 0) {
                            var data = obj.data;
                            wx.config({
                                debug: app.debug || false,
                                appId: data.app_id,
                                timestamp: +data.timestamp,
                                nonceStr: data.noncestr,
                                signature: data.signature,
                                jsApiList: [
                                    'chooseImage',
                                    'uploadImage',
                                    'hideAllNonBaseMenuItem',
                                    'hideOptionMenu'
                                ]
                            });

                            wx.ready(function () {
                                ready.done('wxSDK', callback)
                            });

                        } else {

                        }
                    }
                });
                //ready.done('wxSDK', callback);

                //等待DOM加载完毕,初始化模版元素
                $(document).ready(function () {
                    $('script[type="text/html"]').each(function () {
                        var $x = $(this);
                        var id = $x.attr('id');
                        app.tmp[id] = template.compile($x.html());
                        $x.remove();
                    });
                    setTimeout(function () {
                        loading.show();
                        ready.done('dom', callback);
                    }, 10);
                })
            } else {
                _.getWxAuth();
            }
        },
        info: {
            unionId: null
        },
        api: _.path.wsApi
    };

    return app;
})();

var ex = {
    p: function (obj, type) {
        var ws, br;
        switch (type) {
            case 'html':
                ws = '&nbsp;';
                br = '<br>';
                break;
            case 'log':
                ws = ' ';
                br = '\n';
                break;
        }

        function space(i) {
            if (i == 1)return ws;
            else {
                return ws + space(i - 1);
            }
        }

        var str = '';
        if (typeof obj != 'object') {
            str += obj + space(3) + '[TYPE:' + typeof obj + ']';
        } else {
            for (var i in obj) {
                str += space(1) + i + ': ' + obj[i] + br;

                if (typeof obj[i] == 'object') {
                    for (var j in obj[i]) {
                        str += space(5) + '└─' + space(1) + j + ': ' + obj[i][j] + br;

                        if (typeof obj[i][j] == 'object') {
                            for (var k in obj[i][j]) {
                                str += space(10) + '└─' + space(1) + k + ': ' + obj[i][j][k] + br;
                            }
                            str += br;
                        }
                    }
                    str += br;
                }
            }
            str += br;
        }
        return str;
    }
};